package com.example.canalclientsync.canal.service.impl;

import com.example.canalclientsync.mapstruct.ModelMapping;
import com.example.canalclientsync.canal.mapper.db2.ProjectUserRelationMapper;
import com.example.canalclientsync.canal.po.ProjectMember;
import com.example.canalclientsync.canal.service.DirService;
import com.example.canalclientsync.canal.mapper.db1.DirMapper;
import com.example.canalclientsync.canal.mapper.db1.FileDataRoleMapper;
import com.example.canalclientsync.canal.mapper.db1.ProjectMapper;
import com.example.canalclientsync.canal.po.Dir;
import com.example.canalclientsync.canal.po.FileEditUser;
import com.example.canalclientsync.canal.po.Project;
import com.example.canalclientsync.canal.po.VirtualModel;
import com.example.canalclientsync.canal.service.ModelService;
import com.example.canalclientsync.es.document.EsModel;
import com.example.canalclientsync.es.enums.EsModelClassificationEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author chen.cr
 * @since 2023/9/19
 */
@Service
@Slf4j
public class ModelServiceImpl implements ModelService {

    @Resource
    private DirMapper dirMapper;
    @Resource
    private DirService dirService;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private FileDataRoleMapper fileDataRoleMapper;
    @Resource
    private ProjectUserRelationMapper projectUserRelationMapper;


    /**
     * 根据 VirtualModel 查询相关数据，构建出 EsModel
     *
     * @param model VirtualModel
     * @return EsModel
     */
    @Override
    public EsModel buildFromVirtualModel(VirtualModel model) {
        String tenantId = model.getTenantId();
        Long masterId = model.getMasterId();
        // 所在文件夹
        Dir parentDir = dirMapper.findByMasterIdAndTenantId(masterId, tenantId);
        if (parentDir == null) {
            log.error("查询模型所在文件夹失败，masterId:{}, tenantId:{}", masterId, tenantId);
            return null;
        }
        EsModel esModel = ModelMapping.INSTANCE.model2EsModel(model, parentDir);
        // 填充空间相关信息
        this.fillDataByClassification(esModel, parentDir);

        return esModel;
    }

    /**
     * 根据 VirtualModel 查询相关数据，构建出 EsModel
     *
     * @param model VirtualModel
     * @return EsModel
     */
    @Override
    public EsModel buildFromVirtualModel(VirtualModel model, Dir parentDir) {
        EsModel esModel = ModelMapping.INSTANCE.model2EsModel(model, parentDir);
        // 填充空间相关信息
        this.fillDataByClassification(esModel, parentDir);

        return esModel;
    }


    /**
     * 查询所属空间相关信息
     *
     * @param esModel   模型
     * @param parentDir 模型所在文件夹
     */
    @Override
    public void fillDataByClassification(EsModel esModel, Dir parentDir) {
        // 个人
        if (esModel.getClassification() == EsModelClassificationEnum.IN_PERSONAL.getCode()) {
            Integer userId = dirService.searchUserIdByDir(parentDir);
            if (userId != null) {
                esModel.setBelongedUserId(userId);
            }
        }

        // 部门
        else if (esModel.getClassification() == EsModelClassificationEnum.IN_DEPARTMENT.getCode()) {
            Integer departmentId = dirService.searchLeafDepartmentIdByDir(parentDir);
            if (departmentId != null) {
                esModel.setBelongedDepartmentId(departmentId);
            }
        }

        // 项目
        else if (esModel.getClassification() == EsModelClassificationEnum.IN_PROJECT.getCode()) {
            // 所在项目
            Integer projectId = dirService.searchProjectIdByDir(parentDir);
            esModel.setBelongedProject(this.searchProjectObject(projectId, esModel.getTenantId()));

            // 所在目录
            Dir leafCatalog = dirService.searchLeafCatalogDirByDir(parentDir);
            esModel.setBelongedCatalog(leafCatalog);

            // 编辑者
            List<FileEditUser> fileEditUsers =
                    fileDataRoleMapper.listModelEditUserIdByMasterIdAndTenantId(esModel.getMasterId(), esModel.getTenantId());
            esModel.setEditorUserList(fileEditUsers);
        }

        // 附件所在项目
        else if (esModel.getClassification() == EsModelClassificationEnum.OTHER.getCode()) {
            Project project = projectMapper.findByAttachmentModelIdAndTenantId(esModel.getModelId(), esModel.getTenantId());
            if (project != null) {
                esModel.setAsAttachment(true);
                esModel.setBelongedProject(this.searchProjectObject(project.getId(), esModel.getTenantId()));
            }
        }
    }

    @Override
    public Project searchProjectObject(Integer projectId, String tenantId) {
        if (projectId == null) {
            return null;
        }
        Project project = projectMapper.findByProjectIdAndTenantId(projectId, tenantId);
        if (project != null) {
            // 项目成员
            List<ProjectMember> projectMembers = projectUserRelationMapper.findByProjectIdAndTenantId(projectId, tenantId);
            if (projectMembers != null && projectMembers.size() > 0) {
                // 设置项目负责人
                projectMembers.stream()
                              .filter(x -> x.getChargerFlag() == 1)
                              .map(ProjectMember::getUserId)
                              .findAny()
                              .ifPresent(project::setChargeUserId);
                // 设置项目成员
                Set<Integer> memberUserIds = projectMembers.stream().map(ProjectMember::getUserId).collect(Collectors.toSet());
                project.setMembers(memberUserIds);
            }
        }
        return project;
    }


}
